<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/11 13:08:20 $)
// $RCSfile: functions_knowledgebase.php,v $ : $Revision: 1.25 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Recalculate the number of articles under a kb category
*/
function recountKBCategory($kbcategoryidlist)
{
	global $dbCore;

	$_countlist = array();
	$dbCore->query("SELECT COUNT(*) AS totalitems, kbarticlelinks.kbcategoryid FROM `". TABLE_PREFIX ."kbarticlelinks` AS kbarticlelinks LEFT JOIN `". TABLE_PREFIX ."kbarticles` AS kbarticles ON (kbarticlelinks.kbarticleid = kbarticles.kbarticleid) WHERE kbarticles.articlestatus = '". ARTICLE_PUBLISHED ."' GROUP BY kbarticlelinks.kbcategoryid HAVING kbarticlelinks.kbcategoryid IN(". buildIN($kbcategoryidlist) .");");
	while ($dbCore->nextRecord())
	{
		$_countlist[$dbCore->Record["kbcategoryid"]] = intval($dbCore->Record["totalitems"]);
	}

	foreach ($_countlist as $key=>$val)
	{
		if (!empty($key))
		{
			$dbCore->query("UPDATE LOW_PRIORITY `". TABLE_PREFIX ."kbcategories` SET `totalarticles` = '". intval($val) ."' WHERE `kbcategoryid` = '". intval($key) ."';");
		}
	}

	return true;
}

/**
* Recount the entire tree
*/
function recountEntireKBTree($parentcategoryid = 0)
{
	global $dbCore;

	$_total = 0;
	$_kbcategorylist = array();
	
	//MAHESH: Count public Knowlwdgebase articles even they are in private folder.
	$dbCore->query("SELECT `kbcategoryid` FROM `". TABLE_PREFIX ."kbcategories` WHERE `parentcategoryid` = '". intval($parentcategoryid) ."' ORDER BY `kbcategoryid` DESC;");
	while ($dbCore->nextRecord())
	{
		$_kbcategorylist[] = $dbCore->Record["kbcategoryid"];
	}

	foreach ($_kbcategorylist as $key=>$val)
	{
		$_acount = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems, kbarticlelinks.kbcategoryid FROM `". TABLE_PREFIX ."kbarticlelinks` AS kbarticlelinks LEFT JOIN `". TABLE_PREFIX ."kbarticles` AS kbarticles ON (kbarticlelinks.kbarticleid = kbarticles.kbarticleid) WHERE kbarticles.articlestatus = '". ARTICLE_PUBLISHED ."' GROUP BY kbarticlelinks.kbcategoryid HAVING kbarticlelinks.kbcategoryid = '". intval($val) ."';");

//		$_acount = $dbCore->queryFetch("SELECT COUNT(*) AS `totalitems` FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbcategoryid` = '". intval($val) ."';");

		$_articlecount = recountEntireKBTree($val)+intval($_acount["totalitems"]);
		$_total += $_articlecount; //Mahesh Slaria: KB article Count error.

		$dbCore->query("UPDATE `". TABLE_PREFIX ."kbcategories` SET `totalarticles` = '". intval($_articlecount) ."' WHERE `kbcategoryid` = '". intval($val) ."';", 3);
	}

//	echo "Total For: $parentcategoryid Is: $_total<BR />";

	return $_total;
}

/**
* Generate a rating on an article
*/
function getArticleRating($ratinghits, $ratingcount)
{
	if ($ratinghits == 0)
	{
		return 0;
	} else {
		$totalrating = number_format($ratingcount/$ratinghits, 2);
		$roundrating = round($totalrating);

		$ratingexpl = explode(".", $totalrating);
		if ($ratingexpl[1] > 1 && $ratingexpl[1] <= 25)
		{
			$dec = "25";
		} else if ($ratingexpl[1] > 25 && $ratingexpl[1] <= 50) {
			$dec = "50";
		} else if ($ratingexpl[1] > 50 && $ratingexpl[1] <= 99) {
			$dec = "75";
		}

		if ($roundrating >= 5)
		{
			return "5";
		} else {
			return $roundrating.iif(!empty($dec), ".".$dec);
		}
	}
}

/**
* Return the name of rating image based on given rating
*/
function getRatingImage($rating)
{
	if ($rating == "0")
	{
		return "star_0.gif";
	} else if ($rating == "0.25") {
		return "star_0_25.gif";
	} else if ($rating == "0.50") {
		return "star_0_50.gif";
	} else if ($rating == "0.75") {
		return "star_0_75.gif";
	} else if ($rating == "1") {
		return "star_1.gif";
	} else if ($rating == "1.25") {
		return "star_1_25.gif";
	} else if ($rating == "1.50") {
		return "star_1_50.gif";
	} else if ($rating == "1.75") {
		return "star_1_75.gif";
	} else if ($rating == "2") {
		return "star_2.gif";
	} else if ($rating == "2.25") {
		return "star_2_25.gif";
	} else if ($rating == "2.50") {
		return "star_2_50.gif";
	} else if ($rating == "2.75") {
		return "star_2_75.gif";
	} else if ($rating == "3") {
		return "star_3.gif";
	} else if ($rating == "3.25") {
		return "star_3_25.gif";
	} else if ($rating == "3.50") {
		return "star_3_50.gif";
	} else if ($rating == "3.75") {
		return "star_3_75.gif";
	} else if ($rating == "4") {
		return "star_4.gif";
	} else if ($rating == "4.25") {
		return "star_4_25.gif";
	} else if ($rating == "4.50") {
		return "star_4_50.gif";
	} else if ($rating == "4.75") {
		return "star_4_75.gif";
	} else if ($rating == "5") {
		return "star_5.gif";
	} else {
		return "star_0.gif";
	}	
}

/**
* Update an existing Knowledgebase Article
*/
function updateKBArticle($kbarticleid, $subject, $articlestatus, $displayorder, $articlelinks, $contents)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($articlelinks))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."kbarticles` SET `subject` = '". $dbCore->escape($subject) ."', `isedited` = '1', `editeddateline` = '". DATENOW ."', `editedstaffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `displayorder` = '". intval($displayorder) ."', `articlestatus` = '". $dbCore->escape($articlestatus) ."' WHERE `kbarticleid` = '". intval($kbarticleid) ."';");

	// Update article data
	$dbCore->query("UPDATE `". TABLE_PREFIX ."kbarticledata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `kbarticleid` = '". intval($kbarticleid) ."';");

	// Now the links
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` = '". intval($kbarticleid) ."';");
	$linksql = array();
	foreach ($articlelinks as $key=>$val)
	{
		$linksql[] = "('". intval($val) ."', '". intval($kbarticleid) ."')";
	}
	if (count($linksql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."kbarticlelinks` (`kbcategoryid`, `kbarticleid`) VALUES ". implode(",", $linksql).";");
	}

	rebuildKnowledgebaseJSCache();
	recountEntireKBTree();
//	exit;

	return $kbarticleid;
}

/**
* Insert a new Knowledgebase Article
*/
function insertKBArticle($subject, $articlestatus, $displayorder, $articlelinks, $contents)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."kbarticles` (`staffid`, `subject`, `isedited`, `editeddateline`, `editedstaffid`, `views`, `totalcomments`, `hasattachments`, `dateline`, `displayorder`, `articlestatus`, `articlerating`, `ratinghits`, `ratingcount`) VALUES ('". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($subject) ."', '0', '0', '0', '0', '0', '0', '". DATENOW ."', '". intval($displayorder) ."', '". $dbCore->escape($articlestatus) ."', '0', '0', '0');");
	$kbarticleid = $dbCore->lastInsertId();
	if (!$kbarticleid)
	{
		return false;
	}

	// Now add the article data
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."kbarticledata` (`kbarticleid`, `contents`) VALUES ('". intval($kbarticleid) ."', '". $dbCore->escape($contents) ."');");

	// Now the links
	$linksql = array();
	foreach ($articlelinks as $key=>$val)
	{
		$linksql[] = "('". intval($val) ."', '". intval($kbarticleid) ."')";
	}
	if (count($linksql))
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."kbarticlelinks` (`kbcategoryid`, `kbarticleid`) VALUES ". implode(",", $linksql).";");
	}

	recountEntireKBTree();

	rebuildKnowledgebaseJSCache();

	return $kbarticleid;
}

/**
* Updates the Article Links for the given KB Article
*/
function updateArticleLinks($kbarticleid, $articlelinks)
{
	global $dbCore;

	if (!_is_array($articlelinks))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` = '". intval($kbarticleid) ."';");
	$linksql = array();
	foreach ($articlelinks as $key=>$val)
	{
		$linksql[] = "('". intval($val) ."', '". intval($kbarticleid) ."')";
	}
	if (count($linksql))
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."kbarticlelinks` (`kbcategoryid`, `kbarticleid`) VALUES ". implode(",", $linksql).";");
	}

	rebuildKnowledgebaseJSCache();

	return true;
}

/**
* Delete the given Knowledgebase Articles
*/
function deleteKBArticles($kbarticleidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($kbarticleidlist))
	{
		return false;
	}

	$kbcategoryidlist = array();
	$dbCore->query("SELECT `kbcategoryid` FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	while ($dbCore->nextRecord())
	{
		$kbcategoryidlist[] = $dbCore->Record["kbcategoryid"];
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticledata` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."kbarticlefiles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");

	if (count($kbcategoryidlist))
	{
		recountEntireKBTree();
	}

	rebuildKnowledgebaseJSCache();

	return true;
}


/**
* Deletes a given category
*/
function deleteKnowledgebaseCategory($kbcategoryid)
{
	global $dbCore;

	// Get all child categories
	$kbcategoryidlist = array();
	$kbcategoryidlist = fetchChildCategories($kbcategoryid, ($_temp = array()));
	$kbcategoryidlist[] = $kbcategoryid;

	// First Get all the items under these categories
	$kbarticleidlist = array();
	$dbCore->query("SELECT `kbarticleid` FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbcategoryid` IN (". buildIN($kbcategoryidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (!in_array($dbCore->Record["kbarticleid"], $kbarticleidlist))
		{
			$kbarticleidlist[] = $dbCore->Record["kbarticleid"];			
		}
	}

	if (count($kbarticleidlist))
	{
		// Ok now nuke all the items
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticledata` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticlefiles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");

		deleteArticleFiles($kbarticleidlist);
	}

	// Nuke the categories
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbcategories` WHERE `kbcategoryid` IN (". buildIN($kbcategoryidlist) .");");
	
	// .. the links
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbcategoryid` IN (". buildIN($kbcategoryidlist) .");");

	rebuildKnowledgebaseJSCache();

	return count($kbarticleidlist);
}

/**
* Deletes all files under the specified article list
*/
function deleteArticleFiles($kbarticleidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($kbarticleidlist))
	{
		return false;
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlefiles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	while ($dbCore->nextRecord())
	{
		// Delete all stored files
		$filelocation = "./files/".$dbCore->Record["storedfilename"];
		if (file_exists($filelocation))
		{
			unlink($filelocation);
		}
	}

	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."kbarticlefiles` WHERE `kbarticleid` IN (". buildIN($kbarticleidlist) .");");
	
	return true;
}

/**
* Fetches the ids of all child Categories
*/
function fetchChildCategories($kbcategoryid, &$tslist)
{
	global $dbCore;

	if (empty($tslist))
	{
		$tslist = array();
	}

	$newlist = array();

	$dbCore->query("SELECT `kbcategoryid` FROM `". TABLE_PREFIX ."kbcategories` WHERE `parentcategoryid` = '". intval($kbcategoryid) ."';");
	while($dbCore->nextRecord()) {
		if (!in_array($dbCore->Record["kbcategoryid"], $tslist))
		{
			$tslist[] = $dbCore->Record["kbcategoryid"];
			$newlist[] = $dbCore->Record["kbcategoryid"];
		}
	}

	if (_is_array($newlist))
	{
		foreach ($newlist as $key=>$val)
		{
			fetchChildCategories($val, $tslist);
		}
	}

	return $tslist;
}

/**
* Builds a category array for all knowledgebase categories
*/
function buildKBCategoryData($filtertgroupid = false)
{
	global $dbCore, $_SWIFT;
	
	$categorydata = $categoryidlist = array();
	$catcount = 0;

	if (!empty($filtertgroupid))
	{
		$dbCore->query("SELECT kbcategories.* FROM `". TABLE_PREFIX ."kbcategories` AS kbcategories LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (kbcategories.kbcategoryid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_KNOWLEDGEBASE ."') WHERE tgroupassigns.tgroupid = '". intval($filtertgroupid) ."' ORDER BY kbcategories.kbcategoryid ASC;");
	} else {
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbcategories` ORDER BY `kbcategoryid` ASC;");
	}
	while ($dbCore->nextRecord())
	{
		// We always add the knowledgebase category to list if filtering isnt enabled
		$catcount = count($categorydata[$dbCore->Record["parentcategoryid"]]);
		$categorydata[$dbCore->Record["parentcategoryid"]][$catcount] = $dbCore->Record;
		$categoryidlist[] = $dbCore->Record["kbcategoryid"];
	}

	$result["categorydata"] = $categorydata;
	$result["categoryidlist"] = $categoryidlist;
	return $result;
}

/**
* Builds a list of knowledgebase items from given categories
*/
function buildKBArticleData()
{
	global $dbCore, $_SWIFT;
	
	$articledata = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticles` AS kbarticles LEFT JOIN `". TABLE_PREFIX ."kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) ORDER BY kbarticles.kbarticleid ASC;");
	while ($dbCore->nextRecord())
	{
		$articledata[$dbCore->Record["kbarticleid"]] = $dbCore->Record;
	}

	$catarticledata = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlelinks` ORDER BY `kbarticlelinkid` ASC;", 2);
	while ($dbCore->nextRecord(2))
	{
		$catarticledata[$dbCore->Record2["kbcategoryid"]][] = $articledata[$dbCore->Record2["kbarticleid"]];
	}

	$result = array();
	$result["articledata"] = $articledata;
	$result["catarticledata"] = $catarticledata;

	return $result;
}

/**
* Rebuilds the knowledgebase javascript cache
*/
function rebuildKnowledgebaseJSCache()
{
	global $_SWIFT;

	// ======= FIRST BUILD ALL THE ARTICLE DATA =======
	$resultkb = buildKBArticleData();
	$jsdata = "kbmenuloaded = true;";
	// ======= NOW BUILD THE MENU =======
	$catarticledata = $resultkb["catarticledata"];
	unset($resultkb);
	$jsdata .= SWIFT_CRLF.SWIFT_CRLF;
	$categorydata = buildKBCategoryData(false);
	$jsdata .= 'var MENU_JSCACHE_KNOWLEDGEBASE = ['.SWIFT_CRLF;
	$jsdata .= '	{"popup":1, "popupoff":[0,0], "pos":[0,0], "size":[22,250], "itemoff":[21,0], "leveloff":[10,59],dynamic: true, https_fix_blank_doc:themepath+"blank.html", "delay":600, "style":STYLEPOPUP, "imgsize":[20,22], wrapoff:["level","+previousItem-1px"]},'.SWIFT_CRLF;
	$menudata = "";
	$jsdata .= doKBMenuLoop(0, $categorydata["categorydata"], $catarticledata, $menudata, 1);
	$jsdata .= '];'.SWIFT_CRLF;
	insertToJSCache(MODULE_KNOWLEDGEBASE, $jsdata);
}

/**
* Process the articles and generate relevant JS
*/
function processMenuKBArticles($kbcategoryid, $articledata, $childindent)
{
	$articlecount = count($articledata[$kbcategoryid]);
	if ($articlecount != 0)
	{
		$wrapindex = 0;
		for ($ii=0; $ii<$articlecount; $ii++)
		{
			$childdata = &$articledata[$kbcategoryid][$ii];
			$index = $ii+$index;

			if ($childdata["articlestatus"] == ARTICLE_PUBLISHED)
			{
				$aimage = "icon_menukbarticle.gif";
			} else if ($childdata["articlestatus"] == ARTICLE_DRAFT) {
				$aimage = "icon_menukbdraft.gif";
			} else if ($childdata["articlestatus"] == ARTICLE_PRIVATE) {
				$aimage = "icon_menukbprivate.gif";
			}

			if ($wrapindex >= 15)
			{
				$dowrap = true;
				$wrapindex = 0;
			} else {
				$dowrap = false;
			}
			if ($ii == 0 || $dowrap == true)
			{
				$mstyle = "VSTYLEBORDER";
			} else {
				$mstyle = "VSTYLE";
			}
			

			$menudata2 .= $childindent.'{code:"'. addslashes(preg_replace("#(\r\n|\r|\n)#s", "", iif(strlen($childdata["subject"])>30, substr($childdata["subject"],0,30)."...", $childdata["subject"]))) .'"'. iif($dowrap, ', wrapPoint:true') .', url:"javascript:autoInsertKB('. intval($childdata["kbarticleid"]) .');", "format":{"itemoff":[21,0], "leveloff":[20,90], "image":themepath+"'. $aimage .'", "oimage":themepath+"'. $aimage .'", "style":'. $mstyle .'}';
			$wrapindex++;

			if (($ii+1) == $articlecount)
			{
				$menudata2 .= "}".SWIFT_CRLF;
			} else {
				$menudata2 .= "},".SWIFT_CRLF;
			}
		}

		return $menudata2;
	}
}

/**
* Does a loop on categories and data to generate the menu
*/
function doKBMenuLoop($kbcategoryid, &$categorydata, &$articledata, &$menudata, $indent=0)
{
	global $_SWIFT;
	
	$childcount = count($categorydata[$kbcategoryid]);
	$articlecount = count($articledata[$kbcategoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	$childindent = str_repeat("  ", $indent);
	
	// ======= PROCESS ARTICLES =======
	if ($articlecount != 0)
	{
		$menudata2 = processMenuKBArticles($kbcategoryid, $articledata, $childindent);
	}

	if ($childcount != 0)
	{
		// We itterate through all the childs
		$wrapindex = 0;
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$kbcategoryid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($categorydata[$childdata["kbcategoryid"]]);
			if ($wrapindex >= 15)
			{
				$dowrap = true;
				$wrapindex = 0;
			} else {
				$dowrap = false;
			}
			if ($ii == 0 || $dowrap == true)
			{
				$mstyle = "VSTYLEBORDER";
			} else {
				$mstyle = "VSTYLE";
			}

			$menudata .= $childindent.'{code:"'. addslashes(preg_replace("#(\r\n|\r|\n)#s", "", $childdata["title"])) .'"'. iif($dowrap, ', wrapPoint:true') .', url:"index.php?_m=knowledgebase&_a=managequestions&filter=1&filterkbcategoryid='.$childdata["kbcategoryid"].'", "format":{'. iif($kbcategoryid==0&&$ii==0, '"itemoff":[0,0], ', '"itemoff":[21,0], ') .'"arrow":themepath+"icon_rightarrowgray.gif", "oarrow":themepath+"icon_rightarrowgray.gif", "arrsize":[10,10], "image":themepath+"icon_menufolder.gif", "oimage":themepath+"icon_menufolder.gif", "style":'. $mstyle .'}';
			$wrapindex++;

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				$childindentfw = str_repeat("  ", ($indent+1));
				$childindentfw2 = str_repeat("  ", ($indent+2));
				$menudata .= ",".SWIFT_CRLF;
				$menudata .= $childindentfw.'sub:['.SWIFT_CRLF;
				$menudata .= $childindentfw2 . '{"leveloff":[20,90], wrapoff:[\'level\',\'+previousItem-1px\']},'.SWIFT_CRLF;

				// Yup, do another loop for this
				$index++;
				doKBMenuLoop($childdata["kbcategoryid"], $categorydata, $articledata, $menudata, ($indent+2));
				$menudata .= $childindentfw.']'.SWIFT_CRLF;
				if (($ii+1) == $childcount && $articlecount == 0)
				{
					$menudata .= $childindent.'}'.SWIFT_CRLF;
				} else {
					$menudata .= $childindent.'},'.SWIFT_CRLF;
				}
			} else if ($subchilds == 0 && count($articledata[$childdata["kbcategoryid"]]) != 0) {
				// We have just articles under this category
				$childindentfw = str_repeat("  ", ($indent+1));
				$childindentfw2 = str_repeat("  ", ($indent+2));
				$menudata .= ",".SWIFT_CRLF;
				$menudata .= $childindentfw.'sub:['.SWIFT_CRLF;
				$menudata .= $childindentfw2 . '{"leveloff":[20,90], wrapoff:[\'level\',\'+previousItem-1px\']},'.SWIFT_CRLF;

				// Yup, do another loop for this
				$index++;
				$menudata .= processMenuKBArticles($childdata["kbcategoryid"], $articledata, str_repeat("  ", ($indent+2)));
				$menudata .= $childindentfw.']'.SWIFT_CRLF;
				if (($ii+1) == $childcount && $articlecount == 0)
				{
					$menudata .= $childindent.'}'.SWIFT_CRLF;
				} else {
					$menudata .= $childindent.'},'.SWIFT_CRLF;
				}
			} else {
				if (($ii+1) == $childcount && $articlecount == 0)
				{
					$menudata .= "}".SWIFT_CRLF;
				} else {
					$menudata .= "},".SWIFT_CRLF;
				}
			}
		}
	}

	$menudata .= $menudata2;
	
	return $menudata;
}

/**
* Does a loop on categories to generate tree view data
*/
function doKBCategoryTreeLoop($kbcategoryid, $categorydata, &$nodeclass)
{
	global $_SWIFT;

	$childcount = count($categorydata[$kbcategoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		// We itterate through all the childs
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$kbcategoryid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($categorydata[$childdata["kbcategoryid"]]);

			// Add this node to our parent node
			//$_newnode = &$nodeclass->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $childdata["title"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ <a href='index.php?_m=knowledgebase&_a=insertquestion&kbcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["insertquestion"] ."'>". $_SWIFT["language"]["insertquestion"] ."</a> | <a href='index.php?_m=knowledgebase&_a=insertcategory&parentcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addsubcat"] ."'>". $_SWIFT["language"]["addsubcat"] ."</a> | <a href='index.php?_m=knowledgebase&_a=editcategory&kbcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["edit"] ."'>". $_SWIFT["language"]["edit"] ."</a> | <a onClick='javascript:doConfirm(\"". $_SWIFT["language"]["kbcatdelconfirmmsg"] ."\", \"index.php?_m=knowledgebase&_a=managecategories&do=delete&kbcategoryid=". $childdata["kbcategoryid"] ."\");' href='#' id='blue' title='". $_SWIFT["language"]["delete"] ."'>". $_SWIFT["language"]["delete"] ."</a> ]", 'link' => "", 'icon' => "icon_folderyellow3.gif", 'expandedIcon' => iif(!$subchilds, "icon_folderyellow3.gif", "icon_folderyellow3.gif"), 'expanded' => true)));
			
			// Mahesh Slaria: Added view articles in specific category.
			$_newnode = &$nodeclass->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $childdata["title"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ <a href='index.php?_m=knowledgebase&_a=insertquestion&kbcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["insertquestion"] ."'>". $_SWIFT["language"]["insertquestion"] ."</a> | <a href='index.php?_m=knowledgebase&_a=insertcategory&parentcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addsubcat"] ."'>". $_SWIFT["language"]["addsubcat"] ."</a> | <a href='index.php?_m=knowledgebase&_a=editcategory&kbcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["edit"] ."'>". $_SWIFT["language"]["edit"] ."</a> | <a onClick='javascript:doConfirm(\"". $_SWIFT["language"]["kbcatdelconfirmmsg"] ."\", \"index.php?_m=knowledgebase&_a=managecategories&do=delete&kbcategoryid=". $childdata["kbcategoryid"] ."\");' href='#' id='blue' title='". $_SWIFT["language"]["delete"] ."'>". $_SWIFT["language"]["delete"] ."</a> | <a href='index.php?_m=knowledgebase&_a=managequestions&filter=1&filterkbcategoryid=". $childdata["kbcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["viewarticles"] ."'>". $_SWIFT["language"]["viewarticles"] ."</a> ]", 'link' => "", 'icon' => "icon_folderyellow3.gif", 'expandedIcon' => iif(!$subchilds, "icon_folderyellow3.gif", "icon_folderyellow3.gif"), 'expanded' => true)));
			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				// Yup, do another loop for this
				$index++;
				doKBCategoryTreeLoop($childdata["kbcategoryid"], $categorydata, $_newnode);
			}
		}
	}
	
	return true;
}

/**
* Builds a treeview like category select data
*/
function buildKBCategorySelectData($selectedcatid=false)
{
	global $_SWIFT, $dbCore;

	// Now fetch all the data for all download categories
	$result = buildKBCategoryData();
	$categorydata = $result["categorydata"];

	// Build the option tree for this category
	$_option = doKBCategoryOptionLoop(0, $categorydata, $selectedcatid, 1, ($index = 1), ($_temp = array()));

	$_option[0]["title"] = $_SWIFT["language"]["kbparentcat"];
	$_option[0]["value"] = "0";
	$_option[0]["selected"] = iif(in_array(0, $selectedcatid), true, false);

	return $_option;
}

/**
* Does a loop on categories to generate data
*/
function doKBCategoryOptionLoop($kbcategoryid, $categorydata, $selectedcatid=0, $indent=0, &$index, &$_option)
{
	$childcount = count($categorydata[$kbcategoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		$childindent = str_repeat("  ", $indent);
		$childprefix = $childindent."|- ";

		// Iterate through all childs and build the option list
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$kbcategoryid][$ii];
			$_option[$index]["title"] = $childprefix.$childdata["title"];
			$_option[$index]["value"] = $childdata["kbcategoryid"];
			$_option[$index]["selected"] = iif(in_array($childdata["kbcategoryid"], $selectedcatid), true, false);
			$index++;

			// Does it have any sub childs?
			if (count($categorydata[$childdata["kbcategoryid"]]) > 0)
			{
				// Yup, do another loop for this
				doKBCategoryOptionLoop($childdata["kbcategoryid"], $categorydata, $selectedcatid, ($indent+1), $index, $_option);
			}
		}
	}
	
	return $_option;
}

/**
* Update existing knowledgebase category
*/
function updateKnowledgebaseCategory($kbcategoryid, $parentcategoryid, $title, $displayorder, $categorytype, $tgroupidlist)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."kbcategories` SET `parentcategoryid` = '". intval($parentcategoryid) ."', `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `title` = '". $dbCore->escape($title) ."', `dateline` = '". DATENOW ."', `categorytype` = '". $dbCore->escape($categorytype) ."', `displayorder` = '". intval($displayorder) ."' WHERE `kbcategoryid` = '". intval($kbcategoryid) ."';");

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_KNOWLEDGEBASE, $kbcategoryid, true);

	rebuildKnowledgebaseJSCache();

	return $kbcategoryid;
}

/**
* Inserts a new knowledgebase category
*/
function insertKnowledgebaseCategory($parentcategoryid, $title, $displayorder, $categorytype, $tgroupidlist)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."kbcategories` (`parentcategoryid`, `staffid`, `title`, `dateline`, `totalarticles`, `categorytype`, `displayorder`) VALUES ('". intval($parentcategoryid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($title) ."', '". DATENOW ."', '0', '". $dbCore->escape($categorytype) ."', '". intval($displayorder) ."');");
	$kbcategoryid = $dbCore->lastInsertId();
	if (!$kbcategoryid)
	{
		return false;
	}

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_KNOWLEDGEBASE, $kbcategoryid, false);

	rebuildKnowledgebaseJSCache();

	return $kbcategoryid;
}

/**
* Render the Knowledgebase Category form for INSERT/EDIT
*/
function renderKnowledgebaseCatForm($type)
{
	global $_SWIFT, $dbCore;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["catdetails"]);

	// Title
	printTextRow("title", $_SWIFT["language"]["cattitle"], $_SWIFT["language"]["desc_cattitle"], "text", $_POST["title"]);

	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the knowledgebase category.. will be done only for insert action
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."kbcategories` ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}		
	}
	printNumberRow("displayorder", $_SWIFT["language"]["catdisplayorder"], $_SWIFT["language"]["desc_catdisplayorder"], $_POST["displayorder"]);

	$selectedcatid = array();
	if (!empty($_REQUEST["parentcategoryid"]))
	{
		$selectedcatid[] = $_REQUEST["parentcategoryid"];
	} else {
		$selectedcatid[] = 0;
	}
	$_options = buildKBCategorySelectData($selectedcatid);
	printSelectRow("parentcategoryid", $_SWIFT["language"]["parentcategory"], $_SWIFT["language"]["desc_parentcategory"], $_options);

	$categorytype = false;
	if ($type == INSERT)
	{
		$categorytype = true;
	} else {
		if ($_POST["categorytype"] == SWIFTPUBLIC)
		{
			$categorytype = true;
		}
	}
	printPublicPrivateRow("categorytype", $_SWIFT["language"]["cattype"], $_SWIFT["language"]["desc_cattype"], $categorytype);

	printTGroupRow("tgroupid", $_SWIFT["language"]["templategroups"], $_SWIFT["language"]["desc_templategroups"], $type, TGROUP_KNOWLEDGEBASE, $_POST["kbcategoryid"]);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertcategory"], $_SWIFT["language"]["updatecategory"]));

	printMainTableFooter();

	addHiddenField("_m", "knowledgebase");
	addHiddenField("_a", iif($type==INSERT, "insertcategory", "editcategory"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("kbcategoryid", $_POST["kbcategoryid"]);
	}
	printFormEnd();
}

/**
* Render the Knowledgebase Question form for INSERT/EDIT
*/
function renderKBQuestionForm($type)
{
	global $_SWIFT, $dbCore, $module;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["questiondetails"]);

	// Subject
	printTextRow("subject", $_SWIFT["language"]["questionsubject"], $_SWIFT["language"]["desc_questionsubject"], "text", $_POST["subject"], 60);

	// Article Status
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["published"];
	$options[0]["value"] = ARTICLE_PUBLISHED;
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["draft"];
	$options[1]["value"] = ARTICLE_DRAFT;
	$options[2]["title"] = $_SWIFT["language"]["private"];
	$options[2]["value"] = ARTICLE_PRIVATE;
	printSelectRow("articlestatus", $_SWIFT["language"]["kbarticlestatus"], $_SWIFT["language"]["desc_kbarticlestatus"], $options);

	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the knowledgebase questions.. will be done only for insert action
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."kbarticles` ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}		
	}
	printNumberRow("displayorder", $_SWIFT["language"]["qdisplayorder"], $_SWIFT["language"]["desc_qdisplayorder"], $_POST["displayorder"]);

	$selectedcatid = array();
	if ($type == INSERT)
	{
		if (!empty($_REQUEST["kbcategoryid"]))
		{
			$selectedcatid[] = $_REQUEST["kbcategoryid"];
		} else {
			$selectedcatid[] = 0;
		}
	} else {
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` = '". intval($_POST["kbarticleid"]) ."';");
		while ($dbCore->nextRecord())
		{
			$selectedcatid[] = $dbCore->Record["kbcategoryid"];
		}
	}

	$_options = buildKBCategorySelectData($selectedcatid);
	printSelectMultipleRow("kbcategoryid", $_SWIFT["language"]["qparentcategory"], $_SWIFT["language"]["desc_qparentcategory"], $_options, 5, "96%");


	if (!empty($_GET["ticketid"]) && !empty($_GET["ticketpostid"]) && $module->isRegistered(MODULE_TICKETS))
	{
		// We are adding the data from an existing ticket we just submitted..
		require_once ("./modules/tickets/functions_ticketmain.php");
		$_ticketobj =& new TicketMain($_GET["ticketid"], true);
		if ($_ticketobj->ticket)
		{
			$_ticketpost = $_ticketobj->getTicketPost($_GET["ticketpostid"]);
			$_POST["contents"] = getProcessedHTML($_ticketpost["contents"]);
			addHiddenField("ticketid", $_GET["ticketid"]);
			addHiddenField("ticketpostid", $_GET["ticketpostid"]);
			addHiddenField("departmentid", $_GET["departmentid"]);
			addHiddenField("ticketstatusid", $_GET["ticketstatusid"]);
		}
	}


	printhtmlAreaRow("contents", $_SWIFT["language"]["contents"], $_POST["contents"]);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertquestion"], $_SWIFT["language"]["updatequestion"]));

	printMainTableFooter();

	addHiddenField("_m", "knowledgebase");
	addHiddenField("_a", iif($type==INSERT, "insertquestion", "editquestion"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("kbarticleid", $_POST["kbarticleid"]);
	}
	printFormEnd();
}

/**
* Renders the Category List
*/
function renderCategoryList()
{
	global $dbCore, $template;

	$mcategories = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbcategories` WHERE `parentcategoryid` = '0';");
	while ($dbCore->nextRecord())
	{
		$mcategories[$dbCore->Record["kbcategoryid"]] = $dbCore->Record;
		$mcategories[$dbCore->Record["kbcategoryid"]]["title"] = iif(strlen($dbCore->Record["title"])>12, substr($dbCore->Record["title"],0,12)."..", $dbCore->Record["title"]);
		$mcategories[$dbCore->Record["kbcategoryid"]]["link"] = "index.php?_m=knowledgebase&_a=managequestions&filter=1&filterkbcategoryid=".intval($dbCore->Record["kbcategoryid"]);
	}

	if (count($mcategories))
	{
		$template->assign("catlist", true);
		$template->assign("mcategories", $mcategories);
	}

	return true;
}

/**
* Converts the article into PDF
*/
function makeArticlePDF($kbarticleid, $isstaffcp = false)
{
	global $dbCore, $_SWIFT, $template;

	$_article = getArticle($_GET["kbarticleid"], $isstaffcp);
	if (!$_article)
	{
		return false;
	}

	$_article["contents"] = getProcessedHTML($_article["contents"]);
	$_article["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_article["dateline"]);

	$template->assign("article", $_article);
	if (!$isstaffcp)
	{
		$htmloutput = $template->displayTemplate("kbpdf", TEMPLATE_DB);
	} else {
		$htmloutput = $_article["contents"];
	}
	$str=array(
		'<br />' => '<br>',
		'<hr />' => '<hr>',
		'[r]' => '<red>',
		'[/r]' => '</red>',
		'[l]' => '<blue>',
		'[/l]' => '</blue>',
		'&#8220;' => '"',
		'&#8221;' => '"',
		'&#8222;' => '"',
		'&#8230;' => '...',
		'&#8217;' => '\''
	);
	foreach ($str as $_from => $_to) $htmloutput = str_replace($_from,$_to,$htmloutput);

	require_once ("./includes/functions_pdf.php");
	$pdf = new PDF('P','mm','A4',"",$_SWIFT["swiftpath"]."index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=".$_article["kbarticleid"],false);
	$pdf->Open();
	$pdf->SetCompression(true);
	$pdf->SetCreator(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->SetDisplayMode('real');
	$pdf->SetTitle(_iso2ascii($_article["subject"]));
	$pdf->SetAuthor(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->AddPage();

	$pdf->PutMainTitle(_iso2ascii($_article["subject"]));
	$pdf->PutMinorHeading(_iso2ascii($_SWIFT["language"]["author"]));
	$pdf->PutMinorTitle(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->PutMinorHeading(_iso2ascii($_SWIFT["language"]["createdon"]).edate($_SWIFT["settings"]["dt_datetimeformat"], $_article["dateline"]));
	$pdf->PutLine();

	$pdf->WriteHTML($htmloutput, $htmloutput);

	$pdf->Output(cleanVar(str_replace(" ", "_", $_article["subject"])).".pdf", "D");

	return true;
}

/**
* Get the article and check for user group
*/
function getArticle($kbarticleid, $isstaffcp = false)
{
	global $dbCore, $_SWIFT;

	// First check for the user groups, get all the assigned categories
	$kbcategoryidlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` = '". intval($kbarticleid) ."';");
	while ($dbCore->nextRecord())
	{
		$kbcategoryidlist[] = $dbCore->Record["kbcategoryid"];
	}

	$kbproceed = true;

	// If the article is under a category that is assigned to the group then proceed
	if ($kbproceed)
	{
		$_article = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."kbarticles` AS kbarticles LEFT JOIN `". TABLE_PREFIX ."kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) LEFT JOIN `". TABLE_PREFIX ."kbarticlelinks` AS kbarticlelinks ON (kbarticles.kbarticleid = kbarticlelinks.kbarticleid) WHERE kbarticles.kbarticleid = '". intval($kbarticleid) ."';");
		if (!empty($_article["kbarticleid"]) && ((!$isstaffcp && $_article["articlestatus"] == ARTICLE_PUBLISHED) || $isstaffcp == true))
		{
			return $_article;
		}
	}

	return false;
}
?>